package com.alphas.xixibackendalphas.job;

import com.alphas.xixibackendalphas.model.domain.User;
import com.alphas.xixibackendalphas.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class PreCacheJob {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private RedissonClient redissonClient;
    private List<Long> mainUserList = Arrays.asList(1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,11L,12L,13L,14L,15L,16L,17L,18L,19L,20L,21L,22L,23L,24L,25L,26L,27L,28L);
    @Scheduled(cron = "0 5 17 * * *")
    public void doPreCacheRecommendUser(){
        RLock lock = redissonClient.getLock("xixi:PreCacheJob:doPreCacheRecommendUser:lock");
        try {
            if (lock.tryLock(0,-1, TimeUnit.MILLISECONDS)){
                for (Long userId : mainUserList) {
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                Page<User> page = userService.page(new Page<>(1,20),userQueryWrapper);
                String redisKey = String.format("yupao:user:recommed:%s", userId);
                redisTemplate.opsForValue().set(redisKey,page,30000, TimeUnit.MILLISECONDS);
                }
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        finally {
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }
}
